import axios from 'axios'

import {
  MessageBox
} from 'element-ui';

const request = axios.create({
  baseURL: '/api',
  timeout: 10000,
})

// 响应拦截器
request.interceptors.request.use((config) => {
  return config;
}, (error) => {
  // 处理请求错误
  return Promise.reject(error)
});

const message = new Map([
  [10000, "铺码成功"],
  [-32000, "参数错误"],
  [-32001, "服务器错误"],
  [-32003, "文件类型错误"],
  [-32004, "打开文件失败"],
  [-32005, "码点区域错误"],
  [-32006, "手写码错误"],
  [-32007, "点读码错误"],
  [-32008, "码点错误"],
  [-32009, "创建图片错误"],
  [-32010, "密钥错误"],
  [-32011, "PDF大小参数错误"],
  [-32012, "PDF数量参数错误"],
  [-32013, "PDF未找到错误"],
  [-32014, "下载PDF错误"],
  [-32015, "文件堆积错误"],
  [-32016, "用户点读码错误"],
  [-32017, "用户手写码错误"],
  [-32018, "更新密钥错误"],
])

// 响应拦截器
request.interceptors.response.use((res) => {
  // 在发送请求之前可以做一些事情
  return res;
}, (error) => {
  const status = error.response.status
  if ((/^4[0-9]{2}$/).test(status)) {
    MessageBox.alert(error.message, '请求异常', {
      confirmButtonText: '确定',
    });
  } else if ((/^5[0-9]{2}$/).test(status)) {
    MessageBox.alert(error.message, '服务器异常', {
      confirmButtonText: '确定',
    });
  } else {
    MessageBox.alert(message.get(error.response.data.state.code), error.response.data.state.code, {
      confirmButtonText: '确定',
    });
  }
  // 处理请求错误
  return Promise.reject(error)
})


export default request